<template>
  <div>
    <h1>个人信息管理</h1>
    <el-card>
      <el-form 
        :model="userForm" 
        label-width="120px" 
        :rules="rules" 
        ref="userFormRef"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="userForm.userName" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="用户描述" prop="description">
          <el-input 
            v-model="userForm.description" 
            type="textarea" 
            :rows="3" 
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getUser, updateUser } from '@/api/user'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()
const userForm = ref({
  id: null,
  userName: '',
  email: '',
  description: ''
})

const rules = {
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

const userFormRef = ref(null)

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getUser(userStore.userId)
    userForm.value = {
      id: res.id,
      userName: res.userName,
      email: res.email,
      description: res.description
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 提交表单
const submitForm = () => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await updateUser(userForm.value)
        ElMessage.success('个人信息更新成功')
      } catch (error) {
        console.error('更新用户信息失败:', error)
        ElMessage.error('更新失败')
      }
    }
  })
}

// 组件挂载时获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.el-card {
  margin-top: 20px;
  width: 600px;
}
</style>